//
//  SelectProvinceAndCityViewController.m
//  huisaoche
//
//  Created by 谭谭伟 on 2017/9/19.
//  Copyright © 2017年 Minidai. All rights reserved.
//

#import "MNDSelectProvinceAndCityViewController.h"
#import "MNDCarAddressModel.h"
#import "GpsManager.h"
#import "MNDAssessWebViewController.h"

@interface MNDSelectProvinceAndCityViewController ()<UITableViewDelegate,UITableViewDataSource>
/* 省份 */
@property (weak, nonatomic) IBOutlet UITableView *proTableView;
/* 城市 */
@property (strong, nonatomic) UITableView *cityTableView;
//文件下载
/* 文件内容 */
@property (strong, nonatomic) NSMutableData *fileData;
/* 文件名 */
@property (strong, nonatomic) NSString *fileName;

/* 一级json数组 */
@property (strong, nonatomic) NSArray *jsonArray;
/* 模型数组 */
@property (strong, nonatomic) NSMutableArray *carAddressArray;
/* 索引栏数组 */
@property (strong, nonatomic) NSMutableArray *indexArray;
/* 第一个类型选择 */
@property (strong, nonatomic)  NSIndexPath *proSelectIndex;
//当前城市
@property (weak, nonatomic) IBOutlet UIView *currentCityView;
@property (weak, nonatomic) IBOutlet UILabel *currentCityLabel;
/* <#Annotation#> */
@property (strong, nonatomic) UILabel *firstSelectLabel;
/* 省份 */
@property (strong, nonatomic) NSString *provinceStr;
/* 城市 */
@property (strong, nonatomic) NSString *cityStr;

@end

@implementation MNDSelectProvinceAndCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //判断GPS是否可用
//    CLLocationManager *manager = [[CLLocationManager alloc] init];
//    if(manager.locationServicesEnabled == NO) {
//        self.currentCityLabel.text = @"无法获取当前位置，请打开GPS";
//        self.currentCityView.userInteractionEnabled = NO;
//    }
    //定位
    [[GpsManager sharedGpsManager] getCurrentCity];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getGpsMsg:) name:@"GPS_Location" object:nil];
    
    [self setupUI];
    [self loadAreaData];
    // Do any additional setup after loading the view.
}

- (NSMutableArray *)carAddressArray {
    if (!_carAddressArray) {
        _carAddressArray = [NSMutableArray array];
    }
    return _carAddressArray;
}

- (NSMutableArray *)indexArray {
    if (!_indexArray) {
        _indexArray = [NSMutableArray array];
    }
    return _indexArray;
}

#pragma mark -下载地区文件
- (void)loadAreaData {
    kdeclare_weakself;
    [APIManager sendRequestWithURL:API_AREA_FILE parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            NSString *oldVersion = [UserDefaultsTool objectForKey:kDownLoadAddressVersion];
            NSDictionary *urlDict = responseModel.data;
            NSString *urlStr = [urlDict objectForKey:@"url"];
            NSString *version = [urlDict objectForKey:@"version"];
            if ([oldVersion isEqualToString:version]) {
                
            }else {
                [UserDefaultsTool saveObject:kDownLoadAddressVersion forKey:version];
                [APIManager downloadWithUrl:urlStr onProgress:^(NSProgress *progress) {
                    
                } onSuccess:^(ResponseModel *response) {
                    [weakSelf setupUI];
                } onFailure:^(NSError *error) {
                    
                } onFinish:^(id response, NSError *error) {
                    
                }];
            }
        }else {
            
        }
    } onFailure:^(NSError *error) {
        
    }];
}

#pragma mark -搭建界面

- (void)setupUI {

    self.currentCityView.userInteractionEnabled = NO;
    [self.currentCityView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectCurrentCity:)]];
    
    //Cache目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"area_list.json"];
    //加载JSON文件
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if(!data) {
        NSLog(@"文件未找到");
    }else {
        
        NSError *error;
        
        _jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        //
        self.carAddressArray = [MNDCarAddressModel mj_objectArrayWithKeyValuesArray:_jsonArray];
        for (MNDCarAddressModel *model in _carAddressArray) {
            [self.indexArray addObject:model.initial];
            
        }
        
    }
    
    //设置右侧索引栏属性
    self.proTableView.sectionIndexColor = [UIColor blueColor];
    self.proTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    // -------- 城市tabview --------
    _cityTableView = [[UITableView alloc]initWithFrame:CGRectMake(kScreenWidth, self.navigationController == nil ? 0 : 64, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    _cityTableView.dataSource = self;
    _cityTableView.delegate = self;
    [self.view addSubview:_cityTableView];
    
}

//获取当前位置
- (void)getGpsMsg:(NSNotification *)noti
{
    self.currentCityLabel.text = noti.userInfo[@"cityName"];
    
    self.currentCityView.userInteractionEnabled = YES;
    self.provinceStr = noti.userInfo[@"provinceName"];
    self.cityStr = noti.userInfo[@"cityName"];
    for (MNDCarAddressModel *firstModel in self.carAddressArray) {
        for (MNDCarProvinceModel *provinceModel in firstModel.province) {
            if ([provinceModel.pro_name isEqualToString:self.cityStr]) {
                self.cityAddressId = provinceModel.area_id;
            }else {
                for (MNDCarCityModel *cityModel in provinceModel.citys) {
                    if ([cityModel.area_name isEqualToString:self.cityStr]) {
                        self.cityAddressId = cityModel.area_id;
                    }
                }
            }
        }
    }
}
#pragma mark - Action

//选择当前定位城市
- (void)selectCurrentCity:(UITapGestureRecognizer *)tapGesture {
    
    if (self.addressBlock != nil) {
//        NSString *currentCityStr = self.currentCityLabel.text;
//        if([currentCityStr containsString:@"市"]){
//            currentCityStr = [currentCityStr stringByReplacingOccurrencesOfString:@"市" withString:@""];
//        }
        self.addressBlock(self.provinceStr,self.cityStr);
    }
    if (self.addressAndIdBlock != nil) {
        self.addressAndIdBlock(self.provinceStr, self.cityStr, self.cityAddressId);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_proTableView]) {
        return _carAddressArray.count;
    }else {
        MNDCarAddressModel *addressModel = _carAddressArray[_proSelectIndex.section];
        MNDCarProvinceModel *proModel = addressModel.province[_proSelectIndex.row];
        NSArray *cityModelArray = proModel.citys;
        return cityModelArray.count;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_proTableView]) {
        MNDCarAddressModel *addressModel = _carAddressArray[section];
        
        return addressModel.province.count;
    }else {
        MNDCarAddressModel *addressModel = _carAddressArray[_proSelectIndex.section];
        MNDCarProvinceModel *proModel = addressModel.province[_proSelectIndex.row];
        NSArray *cityModelArray = proModel.citys;
        return cityModelArray.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_proTableView]) {
        MNDCarAddressModel *adressModel = self.carAddressArray[indexPath.section];
        MNDCarProvinceModel *proModel = adressModel.province[indexPath.row];
        static NSString *proCellId = @"proCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:proCellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:proCellId];
        }
        cell.textLabel.text = proModel.pro_name;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = kColorBlack;
        return cell;
    }else {
        MNDCarAddressModel *adressModel = self.carAddressArray[_proSelectIndex.section];
        MNDCarProvinceModel *proModel = adressModel.province[_proSelectIndex.row];
        NSArray *cityArray = proModel.citys;
        MNDCarCityModel *cityModel = cityArray[indexPath.row];
        static NSString *cityCellId = @"cityCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cityCellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cityCellId];
        }
        cell.textLabel.text = cityModel.area_name;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = kColorBlack;
        return cell;
    }
}

//组标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_proTableView]) {
        return _indexArray[section];
    }else {
        return nil;
    }
}
//索引栏标题
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if([tableView isEqual:_proTableView]){
        return _indexArray;
    }else {
        return nil;
    }
}

- (NSInteger )tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    kdeclare_weakself;
    if ([tableView isEqual:_proTableView]) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.textLabel.textColor = kColorDarkOrange;
        _firstSelectLabel.textColor = kColorBlack;
        _firstSelectLabel = cell.textLabel;

        _proSelectIndex = indexPath;
        MNDCarAddressModel *adressModel = self.carAddressArray[_proSelectIndex.section];
        MNDCarProvinceModel *proModel = adressModel.province[_proSelectIndex.row];
        NSArray *cityArray = proModel.citys;
        if (cityArray.count <= 0) {
            if (self.addressBlock != nil) {
                self.addressBlock(proModel.pro_name, proModel.pro_name);
            }
            
            if (self.addressAndIdBlock != nil) {
                self.addressAndIdBlock(proModel.pro_name,proModel.pro_name,proModel.area_id);
            }

            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        [self.cityTableView reloadData];
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.cityTableView.frame = CGRectMake(kScreenWidth*0.5, self.navigationController == nil ? 0 : 64, kScreenWidth*0.5, kScreenHeight);
        }];
    }else {
        MNDCarAddressModel *adressModel = self.carAddressArray[_proSelectIndex.section];
        MNDCarProvinceModel *proModel = adressModel.province[_proSelectIndex.row];
        NSArray *cityArray = proModel.citys;
        MNDCarCityModel *cityModel = cityArray[indexPath.row];
        //        NSString *addressStr = [NSString stringWithFormat:@"%@%@",proModel.pro_name,cityModel.area_name];
        //地名回调
        if (self.addressBlock != nil) {
            self.addressBlock(proModel.pro_name,cityModel.area_name);
        }
        if (self.addressAndIdBlock != nil) {
            if (self.addressAndIdBlock != nil) {
                self.addressAndIdBlock(proModel.pro_name,cityModel.area_name,cityModel.area_id);
            }
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}


//设置组头文字颜色及背景颜色
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section

{
    
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    
    header.textLabel.textColor = kColorLightGray;
    header.textLabel.font = [UIFont systemFontOfSize:12];
    header.contentView.backgroundColor = kColorLightGrayLine;
    
}

//组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 22;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    kdeclare_weakself;
    if ([scrollView isEqual:_proTableView]) {
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.cityTableView.frame = CGRectMake(kScreenWidth, self.navigationController == nil ? 0 : 64, kScreenWidth*0.5, kScreenHeight -64);
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
